from typing import Any, List, Dict

from fastapi import APIRouter, Depends, HTTPException, Query, Body
from sqlalchemy.orm import Session

from app.core.security import get_current_active_user, is_admin, verify_password
from app.crud.user import user
from app.db.session import get_db
from app.models.user import SysUsers
from app.schemas.user import User, UserCreate, UserUpdate, ChangePasswordRequest
from app.utils.decorators import api_response
from app.utils.response import error_response, pagination_response, success_response
from app.utils.password_utils import generate_random_password

router = APIRouter()


@router.get("/users")
@api_response
async def read_users(
    db: Session = Depends(get_db),
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(100, description="返回的记录数"),
    username: str = Query(None, description="用户名（支持模糊查询）"),
    realName: str = Query(None, description="姓名（支持模糊查询）"),
    status: int = Query(None, description="状态：1-启用，0-禁用"),
    current_user: SysUsers = Depends(is_admin),
) -> Any:
    """
    获取所有用户列表（需要管理员权限）
    """
    users = user.get_multi(
        db, 
        skip=skip, 
        limit=limit,
        user_name=username,
        real_name=realName,
        status=status
    )
    total = user.count(
        db,
        user_name=username,
        real_name=realName,
        status=status
    )
    return pagination_response(data=users, total=total)


@router.post("/users")
@api_response
async def create_user(
    *,
    db: Session = Depends(get_db),
    user_in: UserCreate,
    current_user: SysUsers = Depends(is_admin),
) -> Any:
    """
    创建新用户（需要管理员权限）
    """
    # 检查用户名是否已存在
    user_exists = user.get_by_username(db, username=user_in.user_name)
    if user_exists:
        return error_response(
            code=400,
            message="该用户名已被使用"
        )
    
    # 设置创建人信息
    created_by = current_user.user_name if current_user else None
    
    user_obj = user.create(db, obj_in=user_in, created_by=created_by)
    return user_obj


@router.get("/users/me")
@api_response
async def read_user_me(
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    获取当前登录用户信息
    """
    return current_user


@router.get("/users/{user_id}")
@api_response
async def read_user_by_id(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    根据用户ID获取用户信息（普通用户只能获取自己的信息，管理员可以获取任何用户）
    """
    user_obj = user.get(db, id=user_id)
    if not user_obj:
        return error_response(
            code=404,
            message="用户不存在"
        )
    
    if user_obj == current_user or user.is_admin(current_user):
        return user_obj
    
    return error_response(
        code=403,
        message="没有足够的权限访问其他用户的信息"
    )


@router.put("/users/{user_id}")
@api_response
async def update_user(
    *,
    db: Session = Depends(get_db),
    user_id: int,
    user_in: UserUpdate,
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    更新用户信息（普通用户只能更新自己的信息，管理员可以更新任何用户）
    """
    user_obj = user.get(db, id=user_id)
    if not user_obj:
        return error_response(
            code=404,
            message="用户不存在"
        )
    
    # 只有管理员或用户本人可以更新信息
    if not (user_obj == current_user or user.is_admin(current_user)):
        return error_response(
            code=403,
            message="没有足够的权限更新其他用户的信息"
        )
    
    # 设置更新人信息
    updated_by = current_user.user_name if current_user else None
    
    user_obj = user.update(db, db_obj=user_obj, obj_in=user_in, updated_by=updated_by)
    return user_obj


@router.delete("/users/{user_id}")
@api_response
async def delete_user(
    *,
    db: Session = Depends(get_db),
    user_id: int,
    current_user: SysUsers = Depends(is_admin),
) -> Any:
    """
    禁用用户（需要管理员权限）
    """
    user_obj = user.get(db, id=user_id)
    if not user_obj:
        return error_response(
            code=404,
            message="用户不存在"
        )
    
    # 防止管理员禁用自己
    if user_obj.id == current_user.id:
        return error_response(
            code=400,
            message="不能禁用当前登录的管理员账户"
        )
    
    user_obj = user.remove(db, id=user_id)
    return user_obj


@router.post("/users/change-password")
@api_response
async def change_password(
    *,
    db: Session = Depends(get_db),
    password_data: ChangePasswordRequest,
    current_user: SysUsers = Depends(get_current_active_user),
) -> Any:
    """
    修改当前用户的密码
    """
    # 验证旧密码
    if not verify_password(password_data.old_password, current_user.password):
        return error_response(
            code=400,
            message="旧密码不正确"
        )
    
    # 更新密码
    user_update = {"password": password_data.new_password, "version": current_user.version}
    updated_user = user.update(db, db_obj=current_user, obj_in=user_update, updated_by=current_user.user_name)
    
    return success_response(
        message="密码修改成功",
        data={"success": True}
    )


@router.post("/users/{user_id}/reset-password")
@api_response
async def reset_password(
    *,
    db: Session = Depends(get_db),
    user_id: int,
    current_user: SysUsers = Depends(is_admin),
) -> Any:
    """
    重置用户密码（仅管理员可操作）
    """
    user_obj = user.get(db, id=user_id)
    if not user_obj:
        return error_response(
            code=404,
            message="用户不存在"
        )
    
    # 生成随机密码
    random_password = generate_random_password(8)
    
    # 更新用户密码
    user_update = {"password": random_password, "version": user_obj.version}
    user.update(db, db_obj=user_obj, obj_in=user_update, updated_by=current_user.user_name)
    
    return success_response(
        message="密码重置成功",
        data={"password": random_password}
    )